﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AlgoImpl.ConverterAnalyzer;

namespace AlgoImpl
{
    public class StepOneManager : StepManagerAbstract
    {

        public StepOneManager(ShiftRequests sr, int numOfIterations)
        {
            MRequests = sr;
            m_Converter = new Converter();
            m_AlgoExecuter = new AlgoExecuter();
            m_AnalyzerMgr = new AnalyzerManager();
            m_NumOfIterations = numOfIterations;

        }


        protected override void finalize()
        {
            cleanAllRegistrations();
            syncWorkersRequestWithBestAlgoResult();
            updateGlobalResultData(eStepThatGotShift.FIRST);  
        }

        protected override void analyzeResults()
        {
            m_AnalyzerMgr.AnalyzeFirstStep(MRequests);
            MRequests.RandomizeOrderOfShiftsOfWorkers();
        }

        protected override void runAlgo()
        {
            m_AlgoExecuter.Execute();
        }

        protected override void convertToGraph()
        {
            m_Converter.ConvertToGraph(getAllShifts(), getAllWorkers(), MRequests.GetWantedShifts());
        }

        protected override void preperations()
        {
            cleanAllRegistrations();
        }

        private void cleanAllRegistrations()
        {
            List<string> workers = SharedData.Instance.GetAllWorkersIds();
            List<string> shifts = SharedData.Instance.GetAllShiftsIds();
            foreach (string workerId in workers)
            {
                SharedData.Instance.GetWorkerById(workerId).Clear();
            }
            foreach (string shiftId in shifts)
            {
                SharedData.Instance.GetShiftById(shiftId).Clear();
            }
        }

        private void syncWorkersRequestWithBestAlgoResult()
        {
            foreach (KeyValuePair<string, List<string>> kvp in m_AnalyzerMgr.BestRound.ShiftsOfWorker)
            {
                foreach (string str in kvp.Value)
                {
                    SharedData.Instance.GetWorkerById(kvp.Key).AddShift(str);
                    SharedData.Instance.GetShiftById(str).AddWorker(kvp.Key);
                }
            }
        }
    }
}
